<template>
    <div class="page-my-items">
        <div class="">
            <van-nav-bar left-arrow @click-left="$router.back(-1)" :fixed="true" :title="$t('m.MyAds')" style="color:#fff;" />
            <van-tabs class="items-tab-title" @click="clickTab">
                <van-tab :title="items.text" v-for="(items, indexTab) in tabs" :key="indexTab">
                </van-tab>
                <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
                    <van-list
                        v-model="loading"
                        :finished="finished"
                        loading-text=" "
                        @load="getList"
                        class="main-explore buy-list-explore">
                        <div class="user-info-box" v-for="(item, index) in tableData"  @click="goToDetail(item.id, item.status)" :key="index">
                            <!--图片-->
                                <span class="user-info">
                                    <i class="i-icon1">
                                        <span class="items-cover-box">
                                            <img v-lazy="item.cover" :key="item.cover" alt="" :onload="getWidthAndHeight(item, index)" :class="[item.wth == 1 ? 'width-max' : 'height-max']"/>
                                        </span>
                                    </i>
                                    <!--价格-->
                                    <div class="title-price">
                                        <p class="title">{{translateString(item.title)}}</p>
                                        <span>
                                        <div class="price" v-if="item.priceType == 2">{{regexNum(item.price)}}&nbsp;Lks</div>
                                        <div class="price" v-else>{{regexNum(item.price)}}&nbsp;Ks</div>
                                        </span>
                                    </div>
                                    <!--日期，收藏和关注-->
                                    <van-row class="face-icon-box">
                                        <van-col span="8" class="col-left">{{getDate(item.create_datetime)}}</van-col>
                                        <van-col span="16" class="col-right">
                                            <span class="face-icon">
                                                <!--<img src="../../static/img/images/like1.png" />-->
                                                <van-icon name="like" />
                                                <span v-if="item.favotCount">{{regexNum(item.favotCount)}}</span>
                                                <span v-else>0</span>
                                            </span>
                                            <span class="face-icon">
                                                <img src="../../static/img/images/password-eye.png" />
                                                <span v-if="item.viewCount">{{regexNum(item.viewCount)}}</span>
                                                <span v-else>0</span>
                                            </span>
                                        </van-col>
                                    </van-row>
                                    <!--状态-->
                                    <p class="status pending" v-if="item.status == 8">{{$t('m.Reported')}}</p>
                                    <p class="status pending" v-else-if="item.status == 7">{{$t('m.Pendingverfication')}}</p>
                                    <p class="status draft" v-else-if="item.status == 2">{{$t('m.Draft')}}</p>
                                    <p class="status rejected" v-else-if="item.status == 5">Rejected</p>
                                    <!--<p class="status inactive" v-else-if="item.status == 6">Inactive</p>-->
                                    <div class="status sold" v-else-if="item.status == 3">
                                        <!--<img src="../../static/img/images/smile-rate.png" />-->
                                        <!--<span>Please rate buyer</span>-->
                                    </div>
                                </span>
                        </div>
                    </van-list>
                    <div v-show="finished && activeTab != 0" class="no-more">{{$t('m.Nomore')}}~</div>
                    <div v-show="finished && activeTab == 0 && this.tableData.length == 0 && !clickTabLoading">
                        <div class="no-ads">
                            <img src="../../static/img/images/how-works2.png" />
                            <p>{{$t('m.Noadsyet')}}</p>
                            <van-button type="default" class="to-sell" @click="$router.push('/category')">{{$t('m.Sellnow')}}</van-button>
                        </div>
                    </div>

                </van-pull-refresh>
            </van-tabs>
        </div>
    </div>
</template>
<script>
    import {deleteFavourite, getUserSaveList, searchMyItemsList} from '../../static/api/mgc_api'
    import Qs from 'qs'

    export default {
        name: 'MyItems',
        middleware: ['login'],
        data() {
            return {
                loading: false,
                finished: false,
                isLoading: false,
                clickTabLoading: false,
                userId: false,
                activeTab: 0,
                tableData: [],
                pageData: {
                    pageNum: 1,
                    pageSize: 10,
                },
                pageInfo: {
                    totalCount: 0,
                    totalPages: 0
                },
                status: ''
            }
        },
        computed: {
            tabs() {
                if (this.$store.state.store.localLang == 'MM') {
                    return [
                        {value: '1', text: 'ေျကာ္ျငာထားေသာ'}, // 这栏包过3种状态：1, 8, 7
                        {value: '2', text: 'မေျကာ္ျငာထားေသာ'}, // 这栏包过3种状态：6, 2, 5
                        {value: '3', text: 'ေရာင္းခ်ျပီးေသာ'}, // 这栏只有1种状态：3
                        // ACTIVE -- 1
                        // DRAFT -- 2
                        // SOLD -- 3
                        // DELETED -- 4
                        // rejected -- 5
                        // INACTIVE -- 6
                        // PENDING -- 7
                        // REPORTED -- 8
                    ]
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return [
                        {value: '1', text: 'ကြော်ငြာထားသော'},
                        {value: '2', text: 'မကြော်ငြာထားသော'},
                        {value: '3', text: 'ရောင်းချပြီးသော'},
                    ]
                } else {
                    return [
                        {value: '1', text: 'Active'},
                        {value: '2', text: 'Inactive'},
                        {value: '3', text: 'Sold'},
                    ]
                }
            },
        },
        methods: {
            regexNum(v, len, split) {
                split = split || ',', len = Math.abs((+len) % 20 || 2)
                v = parseFloat((v + '').replace(/[^\d\.-]/g, '')).toFixed(len) + ''
                v = parseFloat(v) + ''
                return v.replace(/\d+/, function (v) {
                        var lit = v.length % 3 == 0
                        var index = lit ? v.length - 3 : -1
                        return v.split('').reverse().join('').replace(/\d{3}/g, function (k, l) {
                            return k + ((l == index && lit) ? '' : split)
                        }).split('').reverse().join('')
                    }
                )
            },
            translateString(str){
                if (!str) return ''
                return this.$translateLang(str, 'unicodeTozawgyi');
                // if(this.$store.state.store.localLang == 'MM'){
                //     return this.$translateLang(str,'unicodeTozawgyi');
                // }else {
                //     return str;
                // }
            },
            getDate (value) {
                if(!value){
                    return ''
                }
                var date = new Date(value)
                var Y = date.getFullYear()
                var m = date.getMonth() + 1
                var d = date.getDate()
                if (m < 10) {
                    m = '0' + m
                }
                if (d < 10) {
                    d = '0' + d
                }
                var ts = d + '/' + m + '/' + Y
                return ts
            },
            getWidthAndHeight(e, i) {
                let img = new Image();
                img.src = e.cover
                img.onload = () => {
                    // let str = 'width: ' + img.width + ' ; ' + 'height: ' + img.height + ' ; ' + 'loaded'
                    // console.log(str, 'str')
                    if (img.width > 0 || img.height > 0) {
                        let obj = {
                            wth: null
                        }
                        if (Number(img.width) > Number(img.height)) {
                            obj.wth = 1
                        } else {
                            obj.wth = 0
                        }
                        Object.assign(this.tableData[i], obj)
                    }
                };

            },
            clickTab (index) {
                this.getList(1, index)
                this.activeTab = index
            },
            getList(pageNum, index) {
                // return false
                let  toastL = '';
                if (pageNum == 1) {
                    this.pageData.pageNum = 1;
                    toastL = this.$toast({
                        type: 'loading',
                        mask: true,
                        duration: 0
                    })
                }
                let searchForm = {};
                searchForm.sort = 'create_datetime desc'

                this.clickTabLoading = true
                // 状态见data--tabs:[]
                if (index != undefined) {
                    if (index == 1) {
                        searchForm.status = '[6, 2, 5]'
                        this.status = '[6, 2, 5]'
                    } else if(index == 2) {
                        searchForm.status = '[3]'
                        this.status = '[3]'
                    } else {
                        searchForm.status = '[1, 8, 7]'
                        this.status = '[1, 8, 7]'
                    }
                } else {
                    searchForm.status = this.status || '[1, 8, 7]'
                }

                searchForm.userId = this.userId
                searchForm.pageNum = this.pageData.pageNum
                searchForm.pageSize = this.pageData.pageSize
                let params = Qs.stringify(searchForm, {arrayFormat: 'repeat'})
                searchMyItemsList(params).then((res) => {
                    if (res.data.errorID == 0) {
                        // this.tableData = res.data.object.list || []
                        // wth判断列表图片宽高 start
                        let dataList = res.data.object.list || []
                        for (let i=0; i < dataList.length; i++) {
                            let obj = {
                                wth : null
                            }
                            Object.assign(dataList[i], obj)
                        }
                        // wth判断列表图片宽高 start
                        // // 刷新列表 or 加载更多
                        if (pageNum == 1) {
                            window.scrollTo(0, 0)
                            this.finished = false;
                            // this.tableData = res.data.object.list || []
                            this.tableData = dataList;
                            toastL.clear();
                        } else {
                            // this.tableData = this.tableData.concat(res.data.object.list)
                            this.tableData = this.tableData.concat(dataList)
                        }
                        // // 分页信息配置
                        this.pageInfo.totalPages = res.data.object.pages
                        this.pageInfo.totalCount = res.data.object.total
                        this.pageData.pageNum = this.pageData.pageNum + 1
                        if (this.pageData.pageNum > this.pageInfo.totalPages) {
                            this.finished = true
                        }
                        this.loading = false
                        this.isLoading = false;
                    } else {
                        this.$toast(res.data.message)
                        this.finished = true
                        this.loading = false
                        this.isLoading = false;
                    }
                    this.clickTabLoading = false
                }).catch((e) => {
                    console.log(e)
                    this.$toast('error, please try again later~')
                    this.finished = true
                    this.loading = false
                    this.isLoading = false;
                    this.clickTabLoading = false
                })
            },
            goToDetail(id, status) {
                this.$router.push({
                    path:'/buydetail',
                    query:{
                        id: id,
                        status: status,
                        myItems: true,
                    }
                })
            },
            onRefresh(){
                this.getList(1)
            },

            getUserId() {
                let userInfo = localStorage.getItem('userInfo') || ''
                if (userInfo) {
                    userInfo = JSON.parse(userInfo);
                    this.userId = userInfo.id;
                }
            },
        },
        mounted() {
            this.getUserId();
        },
        beforeRouteLeave (to, from, next) {
           if (to.path == '/sell') {
                this.$router.replace('/user/myaccount')
           } else {
                next()
           }
        }
    }
</script>

<style>
    .page-my-items .van-nav-bar{
        /*background-color: #FF9900;*/
        background-color: #f2f2f2;
        color: #333;
        z-index: 9;
    }
    .page-my-items .van-nav-bar .van-icon{
        color: #C8C8C8;
        margin-right: 15px;
        font-size: 18px;
    }
    .page-my-items .van-nav-bar .van-nav-bar__title{
        color: #333;
    }
    .page-my-items  .van-list__loading{
        width: 100%;
        /*border-top: 1px solid #F2F2F2;*/
    }
    .page-my-items .van-tabs.items-tab-title .van-tabs__wrap{
        position: fixed;
        width: 100%;
        top: 45px;
    }
    .page-my-items .van-tabs.items-tab-title .van-tabs__content{
        margin-top: 44px;
    }
    .page-my-items .van-tabs.items-tab-title .van-tab--active{
        color: #FF9900;
    }
    .page-my-items .van-tabs.items-tab-title .van-tabs__line{
        background-color: #FF9900;
    }
    .page-my-items .van-tabs.items-tab-title .van-ellipsis{
        text-overflow: initial;
        overflow: initial;
    }
    .page-my-items .to-sell.van-button--default{
        background: #FF9900;
        color: #fff;
        border-width: 0;
        padding: 0 25px;
        margin-top: 12px;
    }
    .face-icon .van-icon-like{
        font-size: 18px;
        margin: 4px 2px 0 0;
    }
</style>
<style scoped>
    .user-info-box {
        padding: 15px 0 15px 4%;
        padding: 10px 4%;
        border-top: 1px solid #F2F2F2;
        /*border-bottom: 1px solid #F2F2F2;*/
        color: rgb(102, 102, 102);

    }
    .user-info {
        position: relative;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        padding-left: 4.1em;
        min-height: 50px;
        line-height: 150%;
        justify-content: space-around;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
    }
    .user-info .i-icon1{
        position: absolute;
        top: 50%;
        left: 0;
        display: inline-block;
        width: 50px;
        height: 50px;
        margin-top: -25px;
    }
    .user-info .title-price {
        display: flex;
        justify-content: space-between;
    }
    .user-info p.title{
        font-size: 16px;
        font-weight: 400;
        font-style: normal;
        text-decoration: none;
        padding: 0;
        margin: 0;
        text-align: left;
        flex: 1;
        max-width: 60%;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        color: #000;
    }
    .user-info i img{
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1;
        width: 100%;
    }
    .user-info i img.width-max{
        width: auto;
        left: 50%;
        right: auto;
        height: 100%;
        -webkit-transform: translate(-50%);
        transform: translate(-50%);
    }
    .user-info i img.height-max{
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    .face-icon-box {
        height: 24px;
    }
    .face-icon-box img{
        display: inline-block;
        height: 24px;
        width:auto;
    }
    .face-icon {
        display:inline-flex;
        height:100%;
        margin-right: 6px;
    }
    .like-icon{
        position: relative;
        width: 24px;
    }
    .col-left{
        font-size: 12px;
    }
    .col-right{
        text-align: right;
        display: flex;
        justify-content: flex-end;
    }
    .no-more{
        border-top: 1px solid #F2F2F2;
        height: 50px;
        line-height: 50px;
        color: #909399;
        text-align: center;
    }
    .no-ads{
        padding-top: 60px;
        text-align: center;
    }
    .no-ads img{
        display: block;
        margin: 0 auto;
        width: 70%;
        max-width: 267px;
    }
    .no-ads p{
        margin: 40px 0 0 0;
        text-align: center;
    }
    .items-cover-box{
        width: 100%;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        background: #f0f0f0;
        position: relative;
        z-index: 0;
        height: 0;
        padding: 0 0 100%;
        overflow: hidden;
        border-radius: 6px;
    }
    .items-cover-box::before{content: "Tolymoly";
        position: absolute;
        top: 50%;
        bottom: 0;
        right: 0;
        left: 0;
        text-align: center;
        background: #f0f0f0;
        font-size: .5rem;
        font-weight: 700;
        color: #c0bfbf;
        z-index: -1;
        margin-top: -12px;
        font-style: initial;
    }
    .status{
        font-size: 14px;
        margin: 0;
    }
    .status.draft{
        color: rgb(43, 181, 112);
    }
    .status.rejected{
        color: rgb(219, 55, 67);
    }
    .status.inactive{
        color: rgb(234, 93, 93);
    }
    .status.pending{
        color: rgb(255, 136, 32);
    }
    .status.sold{
        height: 18px;
        line-height: 18px;
        overflow: hidden;
        display: flex;
    }
    .status.sold img{
        height: 18px;
        width: 18px;
        margin-right: 5px;
    }
</style>
